package com.wdh.kjs.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.utils.L;
import com.wdh.kjs.Adapter.InvestmentListAdapter;
import com.wdh.kjs.Adapter.ListViewForScrollView;
import com.wdh.kjs.Adapter.MessageEditAdapter;
import com.wdh.kjs.Adapter.MessageListAdapter;
import com.wdh.kjs.R;
import com.wdh.kjs.fragment.MyAccountFragment;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by CQH on 2016/4/21.
 */
public class MyAccountTopTurnActivity extends Activity implements View.OnClickListener {
    private Intent intent = new Intent();
    private LinearLayout station_message_return;
    private TextView station_message_edit;
    private PullToRefreshListView listview;
    private MessageListAdapter investmentListAdapter;
    private List<HashMap<String, String>> datas=new ArrayList<>();;
    private String partyId;
    public static int page = 1;
    public static int rows = 9;
    private JsonModel_my jsonModel_my;
    public static int totalrecords = 0;
    public  boolean mLoading = true;
    public int position_2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_station_message);
        SharedPreferences share = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = share.getString("loginToken", "");
        page = 1;
        intent.putExtra("unReadTotal","0");
        setResult(111,intent);
        initview();
        intweb();
        detail();
    }

//    @Override
//    protected void onStop() {
//        super.onStop();
//        intweb();
////        investmentListAdapter.notifyDataSetChanged();
//
//    }

    private void detail(){
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                position_2 = i-1;
                intent.putExtra("userReceiveMessageId",datas.get(i-1).get("userReceiveMessageId"));
                intent.setClass(MyAccountTopTurnActivity.this,MessageDetailsActivity.class);
                startActivityForResult(intent,5);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==5){
            if(resultCode==3){
                datas.get(position_2).put("userMessageState","1");
                investmentListAdapter.notifyDataSetChanged();
            }
        }

    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows + "");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_STSTION_MESSAGE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {
                    totalrecords = jsonModel_my.getTotalrecords();
                    Log.i("msg","totalrecords_1 "+totalrecords);
                    initwidge();
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {

                ToastUtils.showShort(MyAccountTopTurnActivity.this, "网络异常！");
            }
        });

    }

    private void initview() {
        station_message_return = (LinearLayout) findViewById(R.id.station_message_return);
        station_message_edit = (TextView) findViewById(R.id.station_message_edit);
        station_message_return.setOnClickListener(this);
        station_message_edit.setOnClickListener(this);

        listview = (PullToRefreshListView) findViewById(R.id.activity_message_listview);

    }

    private void initwidge() {

        investmentListAdapter = new MessageListAdapter(this, initListViewData());
        listview.setAdapter(investmentListAdapter);
        listview.setMode(PullToRefreshBase.Mode.BOTH);
        listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            // 下拉Pulling Down
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }

            // 上拉Pulling Up
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                new GetDataTask().execute();
            }
        });
    }

    private List<HashMap<String, String>> initListViewData() {
        datas = new ArrayList<>();
        for (int i = 0; i < jsonModel_my.getMessageList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            if(jsonModel_my.getMessageList().get(i).getUserMessageDel().equals("0")){
                hashMap.put("tv_message_title", jsonModel_my.getMessageList().get(i).getUserMessageTitle());
                hashMap.put("tv_message_time", jsonModel_my.getMessageList().get(i).getCreatedTxStamp().substring(0,10));
                hashMap.put("userReceiveMessageId", jsonModel_my.getMessageList().get(i).getUserReceiveMessageId());
                hashMap.put("userMessageState", jsonModel_my.getMessageList().get(i).getUserMessageState());
                datas.add(hashMap);
            }
        }
        return datas;

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.station_message_return:
                finish();
                break;
            case R.id.station_message_edit:
//                intent.putExtra("list",(Serializable)datas);
//                intent.setClass(this, MessageEditActivity.class);
                intent = new Intent(this, MessageEditActivity.class);
                startActivity(intent);
                break;
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {
                Log.i("msg","totalrecords_2 "+totalrecords+datas.size());
                page += 1;
                try {
                    getMoreList();
                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(MyAccountTopTurnActivity.this, "已无更多数据！");
            listview.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("page", page+"");
        params.addBodyParameter("rows", rows+"");
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_STSTION_MESSAGE, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                if (jsonModel_my.success) {

                    Log.i("ddd","totalrecords_3 "+jsonModel_my.getMessageList().size()+" "+responseInfo.result);

                    if (jsonModel_my != null&& jsonModel_my.getMessageList().size()> 0) {
                        moreListViewData();
                    } else{
                        page -= 1;
                        ToastUtils.showShort(MyAccountTopTurnActivity.this, "没有更多数据！");
                    }
                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(MyAccountTopTurnActivity.this, "网络异常！");
            }
        });
    }

    private void moreListViewData() {
        for (int i = 0; i < jsonModel_my.getMessageList().size(); i++) {
            HashMap<String, String> hashMap = new HashMap<>();
            if(jsonModel_my.getMessageList().get(i).getUserMessageDel().equals("0")){
                hashMap.put("tv_message_title", jsonModel_my.getMessageList().get(i).getUserMessageTitle());
                hashMap.put("tv_message_time", jsonModel_my.getMessageList().get(i).getCreatedTxStamp().substring(0,10));
                hashMap.put("userReceiveMessageId", jsonModel_my.getMessageList().get(i).getUserReceiveMessageId());
                hashMap.put("userMessageState", jsonModel_my.getMessageList().get(i).getUserMessageState());
                datas.add(hashMap);
            }
        }
        if (datas.size() == totalrecords)
            mLoading = false;
         investmentListAdapter.notifyDataSetChanged();
    }
}
